import React, { useState } from 'react';
import { 
  Form, Input, Upload, Button, Steps, Checkbox, 
  InputNumber, DatePicker, Card, Space, Typography, Divider,
  Image, message
} from 'antd';
import { UploadOutlined, ArrowRightOutlined, ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons';
import 'antd/dist/reset.css';

const { Step } = Steps;
const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;

// 图片上传最大数量限制 - 封面图
const MAX_COVER_IMAGES = 1;

// 获取Base64图片（预览用）
const getBase64 = file =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });

// 图片上传前的校验
const beforeUpload = (file, maxSize = 5) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传JPG/PNG格式的图片!');
    return false;
  }
  
  const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
  if (!isLtMaxSize) {
    message.error(`图片大小不能超过${maxSize}MB!`);
    return false;
  }
  
  return true;
};

// 模拟产品数据
const productList = [
  { id: 1, name: '推拿按摩（60分钟）', image: 'https://picsum.photos/id/133/48/48' },
  { id: 2, name: '针灸治疗（单次）', image: 'https://picsum.photos/id/225/48/48' },
  { id: 3, name: '艾草精油（100ml）', image: 'https://picsum.photos/id/106/48/48' },
  { id: 4, name: '拔罐疗法（30分钟）', image: 'https://picsum.photos/id/119/48/48' },
  { id: 5, name: '中药熏蒸（45分钟）', image: 'https://picsum.photos/id/129/48/48' },
];

export const AddProductPackage = () => {
  // 当前步骤状态
  const [currentStep, setCurrentStep] = useState(0);
  // 表单数据
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    originalPrice: 0,
    sellingPrice: 0,
    discountDescription: '',
    startDate: null,
    endDate: null,
    usageRules: ''
  });
  
  // 封面图片相关状态
  const [coverFileList, setCoverFileList] = useState([]);
  const [previewImage, setPreviewImage] = useState('');
  const [previewOpen, setPreviewOpen] = useState(false);
  const [selectedProducts, setSelectedProducts] = useState([]);
  
  // 步骤配置
  const steps = [
    { title: '基础信息' },
    { title: '关联产品' },
    { title: '价格策略' },
    { title: '适用规则' },
  ];

  // 处理输入变化
  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理产品选择
  const handleProductChange = (checkedValues) => {
    setSelectedProducts(checkedValues);
  };

  // 下一步
  const nextStep = () => {
    setCurrentStep(prev => Math.min(prev + 1, steps.length - 1));
  };

  // 上一步
  const prevStep = () => {
    setCurrentStep(prev => Math.max(prev - 1, 0));
  };

  // 处理图片预览
  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
  };

  // 处理封面图片上传变化
  const handleCoverImageChange = ({ fileList: newFileList }) => {
    // 过滤掉已移除的文件并限制数量
    const filteredList = newFileList
      .filter(file => file.status !== 'removed')
      .slice(0, MAX_COVER_IMAGES); // 只保留第一张
    setCoverFileList(filteredList);
  };

  // 上传按钮通用组件
  const renderUploadButton = (text, icon = <PlusOutlined />) => (
    <button style={{ border: 0, background: 'none' }} type="button">
      {icon}
      <div style={{ marginTop: 8 }}>{text}</div>
    </button>
  );

  // 提交表单
  const handleSubmit = () => {
    // 处理封面图片数据
    const coverImage = coverFileList.length > 0 ? 
      coverFileList[0].response?.data?.url || coverFileList[0].url : '';
    
    const submitData = {
      ...formData,
      coverImage,
      selectedProducts
    };
    
    console.log('套餐创建数据:', submitData);
    // 这里可以添加API调用逻辑
    alert('套餐创建成功！');
  };

  return (
    <div className=" mx-auto p-4 md:p-6 max-w-7xl bg-gray-50 min-h-screen py-8">
      {/* 页面标题 */}
      <div style={{marginBottom:10}}>
        <Title level={2} style={{ color: '#2F4F4F' }}>产品套餐创建</Title>
        <Paragraph style={{ color: '#666' }}>组合理疗项目与产品，打造专属优惠套餐</Paragraph>
      </div>

      {/* 步骤导航 */}
      <Card className="mb-6" style={{ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',marginBottom:10 }}>
        <Steps current={currentStep} className="py-4">
          {steps.map((step, index) => (
            <Step key={index} title={step.title} />
          ))}
        </Steps>
      </Card>

      {/* 步骤内容 */}
      <Card className="mb-6"  style={{ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',marginBottom:10 }}>
        <div className="p-6">
          {/* 步骤1：基础信息 */}
          {currentStep === 0 && (
            <div>
              <Title level={3} style={{ color: '#2F4F4F', marginBottom: 24 }}>套餐基础信息</Title>
              
              <Form layout="vertical" className="space-y-4">
                <Form.Item
                  label="套餐名称"
                  rules={[{ required: true, message: '请输入套餐名称' }]}
                >
                  <Input
                    placeholder="如：四季养生调理套餐"
                    value={formData.name}
                    onChange={(e) => handleInputChange('name', e.target.value)}
                    style={{ 
                      borderColor: '#ddd',
                      '&:focus': {
                        borderColor: '#8B5A2B',
                        boxShadow: '0 0 0 2px rgba(139, 90, 43, 0.2)'
                      }
                    }}
                  />
                </Form.Item>
                
                <Form.Item
                  label="套餐简介"
                  rules={[{ required: true, message: '请输入套餐简介' }]}
                >
                  <TextArea
                    rows={3}
                    placeholder="简要描述套餐特色与适用人群"
                    value={formData.description}
                    onChange={(e) => handleInputChange('description', e.target.value)}
                    style={{ 
                      borderColor: '#ddd',
                      '&:focus': {
                        borderColor: '#8B5A2B',
                        boxShadow: '0 0 0 2px rgba(139, 90, 43, 0.2)'
                      }
                    }}
                  />
                </Form.Item>
                
                <Form.Item
                  label={
                    <span>
                      套餐封面 <span style={{ color: '#ff4d4f' }}>*</span>
                    </span>
                  }
                  rules={[{ required: true, message: '请上传套餐封面图片' }]}
                >
                  <div>
                    <Text type="secondary" style={{ fontSize: '13px', marginBottom: 12, display: 'block' }}>
                      封面图：请上传一张清晰的套餐主图，将作为套餐展示的主要图片
                    </Text>
                    <Upload
                      action="http://116.62.217.197:9921/api/Upload/Upload_Goods_Cover"
                      listType="picture-card"
                      fileList={coverFileList}
                      onPreview={handlePreview}
                      onChange={handleCoverImageChange}
                      beforeUpload={(file) => beforeUpload(file)}
                      maxCount={MAX_COVER_IMAGES}
                    >
                      {coverFileList.length >= MAX_COVER_IMAGES ? null : renderUploadButton('上传封面')}
                    </Upload>
                    {/* 图片预览组件 */}
                    {previewImage && (
                      <Image
                        wrapperStyle={{ display: 'none' }}
                        preview={{
                          visible: previewOpen,
                          onVisibleChange: visible => setPreviewOpen(visible),
                          afterOpenChange: visible => !visible && setPreviewImage(''),
                        }}
                        src={previewImage}
                      />
                    )}
                  </div>
                </Form.Item>
              </Form>
            </div>
          )}

          {/* 步骤2：关联产品 */}
          {currentStep === 1 && (
            <div>
              <Title level={3} style={{ color: '#2F4F4F', marginBottom: 24 }}>关联产品/项目</Title>
              <Paragraph style={{ color: '#666', marginBottom: 16 }}>
                选择套餐包含的理疗项目或产品，支持多选
              </Paragraph>
              
              <div style={{ 
                maxHeight: '300px', 
                overflowY: 'auto', 
                border: '1px solid #ddd', 
                borderRadius: '4px', 
                padding: '16px',
                marginBottom: 24
              }}>
                {productList.map(product => (
                  <div 
                    key={product.id} 
                    style={{ 
                      display: 'flex', 
                      alignItems: 'center', 
                      marginBottom: '12px',
                      paddingBottom: '12px',
                      borderBottom: product.id !== productList.length ? '1px dashed #f0f0f0' : 'none'
                    }}
                  >
                    <Checkbox 
                      value={product.id}
                      checked={selectedProducts.includes(product.id)}
                      onChange={(e) => {
                        const checkedValues = e.target.checked 
                          ? [...selectedProducts, product.id]
                          : selectedProducts.filter(id => id !== product.id);
                        handleProductChange(checkedValues);
                      }}
                    />
                    <img 
                      src={product.image} 
                      alt={product.name} 
                      style={{ 
                        width: '40px', 
                        height: '40px', 
                        borderRadius: '4px', 
                        margin: '0 12px' 
                      }}
                    />
                    <span>{product.name}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 步骤3：价格策略 */}
          {currentStep === 2 && (
            <div>
              <Title level={3} style={{ color: '#2F4F4F', marginBottom: 24 }}>价格与优惠设置</Title>
              
              <Form layout="vertical" className="space-y-4">
                <Form.Item
                  label="套餐原价"
                  rules={[{ required: true, message: '请输入套餐原价' }]}
                >
                  <InputNumber
                    placeholder="组合产品总价"
                    value={formData.originalPrice}
                    onChange={(value) => handleInputChange('originalPrice', value)}
                    style={{ width: '100%', borderColor: '#ddd' }}
                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={value => value.replace(/\¥\s?|(,*)/g, '')}
                  />
                </Form.Item>
                
                <Form.Item
                  label="套餐售价"
                  rules={[{ required: true, message: '请输入套餐售价' }]}
                >
                  <InputNumber
                    placeholder="客户实际支付价格"
                    value={formData.sellingPrice}
                    onChange={(value) => handleInputChange('sellingPrice', value)}
                    style={{ width: '100%', borderColor: '#ddd' }}
                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={value => value.replace(/\¥\s?|(,*)/g, '')}
                  />
                </Form.Item>
                
                <Form.Item
                  label="优惠说明"
                >
                  <TextArea
                    rows={2}
                    placeholder="如：立省XX元、买赠活动等"
                    value={formData.discountDescription}
                    onChange={(e) => handleInputChange('discountDescription', e.target.value)}
                    style={{ borderColor: '#ddd' }}
                  />
                </Form.Item>
              </Form>
            </div>
          )}

          {/* 步骤4：适用规则 */}
          {currentStep === 3 && (
            <div>
              <Title level={3} style={{ color: '#2F4F4F', marginBottom: 24 }}>套餐使用规则</Title>
              
              <Form layout="vertical" className="space-y-4">
                <Form.Item
                  label="有效期"
                  rules={[{ required: true, message: '请选择有效期' }]}
                >
                  <Space>
                    <DatePicker
                      value={formData.startDate}
                      onChange={(date) => handleInputChange('startDate', date)}
                      placeholder="开始日期"
                      style={{ borderColor: '#ddd' }}
                    />
                    <Text>至</Text>
                    <DatePicker
                      value={formData.endDate}
                      onChange={(date) => handleInputChange('endDate', date)}
                      placeholder="结束日期"
                      style={{ borderColor: '#ddd' }}
                    />
                  </Space>
                </Form.Item>
                
                <Form.Item
                  label="使用限制"
                  rules={[{ required: true, message: '请输入使用限制' }]}
                >
                  <TextArea
                    rows={3}
                    placeholder="如：每人限购1份、需提前预约等"
                    value={formData.usageRules}
                    onChange={(e) => handleInputChange('usageRules', e.target.value)}
                    style={{ borderColor: '#ddd' }}
                  />
                </Form.Item>
              </Form>
            </div>
          )}
        </div>
      </Card>

      {/* 操作按钮 */}
      <div style={{ textAlign: 'right' }}>
        {currentStep > 0 ? (
          <Button 
            onClick={prevStep} 
            style={{ marginRight: 8 }}
            icon={<ArrowLeftOutlined />}
          >
            上一步
          </Button>
        ) : null}
        
        {currentStep < steps.length - 1 ? (
          <Button 
            type="primary" 
            onClick={nextStep}
            icon={<ArrowRightOutlined />}
            style={{ backgroundColor: '#8B5A2B', borderColor: '#8B5A2B' }}
          >
            下一步
          </Button>
        ) : (
          <Button 
            type="primary" 
            onClick={handleSubmit}
            style={{ backgroundColor: '#8B5A2B', borderColor: '#8B5A2B' }}
          >
            完成创建
          </Button>
        )}
      </div>
    </div>
  );
};
    